package store.lunangangster.nodeflow.parser.base.expression;

import store.lunangangster.nodeflow.enums.NodeType;
import store.lunangangster.nodeflow.exception.ExecutableItemNotFoundException;
import store.lunangangster.nodeflow.exception.IllegalFlowExpressionException;
import store.lunangangster.nodeflow.rt.element.Executable;

/**
 * <p>
 * 针对Flow中的value中的Expression解析结果节点，例如：每个按','分割的都会作为一个<code>ExpressionNode</code>； 又如对于包含了条件表达式的表达式："a, b(c|d),
 * e"，b(c|d)也将被解析为一个ExpressionNode。
 * </p>
 *
 * @author cwk
 * @version 1.0
 */
public class ExpressionNode {

	/**
	 * 解析当前的expression，从FlowBus中找到一个可执行对象(Node | Flow | Chain)
	 *
   * @param expression	Flow表达式
	 * @return	解析出的可执行对象
	 * @throws ExecutableItemNotFoundException	找不到表达式对应的Node or Chain
	 * @throws IllegalFlowExpressionException		表达式错误，解析失败
	 */
	public static Executable resolve(String expression) throws ExecutableItemNotFoundException, IllegalFlowExpressionException {
		if (ExpressionParserHelper.isNodeExpression(expression, NodeType.NODE_COMMON)) {
			return ExpressionParserHelper.resolveCommonExpression(expression);
		} else if (ExpressionParserHelper.isNodeExpression(expression, NodeType.NODE_IF)) {
			return ExpressionParserHelper.resolveIfExpression(expression);
		} else if (ExpressionParserHelper.isNodeExpression(expression, NodeType.NODE_FOR)) {
			return ExpressionParserHelper.resolveForExpression(expression);
		} else if (ExpressionParserHelper.isNodeExpression(expression, NodeType.NODE_WHILE)) {
			return ExpressionParserHelper.resolveWhileExpression(expression);
		} else if (ExpressionParserHelper.isNodeExpression(expression, NodeType.NODE_SWITCH)) {
			return ExpressionParserHelper.resolveSwitchExpression(expression);
		}
		throw new IllegalFlowExpressionException(String.format("Expression resolve failed: find no available flow type for expression \"%s\"", expression));
	}

}
